<?php

namespace app\api\model;

use app\common\exception\Parameter;
use app\common\LogService;
use app\common\Notification;
use app\common\ScoreLog;
use Exception;
use think\facade\Db;
use think\facade\Log;
use think\Model;

class Good extends Model
{
    public function getImagesAttr($val)
    {
        if (!is_array($val)) {
            $val = explode(',', $val);
        }
        foreach ($val as &$j) {
            $noimg =  '/static/images/noimg.png';
            $path = app()->getRootPath() . '/public' . $j;
            if ($j && file_exists($path)) {
                $j = addHost($j);
            } else {
                $j = addHost($noimg);
            }
        }
        return $val;
    }
    public static function list($type)
    {
        if ($type == -1) {
            $list =  self::field('id , good_name , score ,stock,images')->where(['status' => 1])->paginate(10);
        } else {
            $list =  self::field('id , good_name , score ,stock,images')->where(['good_type' => $type, 'status' => 1])->paginate(10);
        }
        $user = User::field('score,avator')->find(getUid());
        return ['data' => $list, 'user' => $user];
    }
    public function pay($id)
    {

        $good = self::find($id);
        if (!$good)  throw new Parameter(['msg' => '商品不存在']);
        $recordLog = function ($status, $message = '') use ($id) {
            LogService::record(
                name: '兑换商品',
                user_id: getUid(),
                target_id: $id,
                status: $status,
                content: $message == '' ? [] : ['reason' => $message],
            );
        };
        $uid = getUid();
        $user = User::find($uid);
        if ($user->score < $good->score)  throw new Exception('积分不够');
        $reward = $this->callRewardVal($user, $good);
        $good_type = $good['good_type'];
        $status = 1;
        Db::startTrans();
        try {
            if ($good_type == 2) {
                Db::table('gn_fake')->where('fake', $reward)->update(['is_load' => 1]);
            } else if ($good_type == 1) {
                Db::table('gn_user')->where('id', $uid)->update(['vip_time' => $reward]);
            } else if ($good_type == 3) {
                $status = 0;
            }
            $param = [
                'good_id' => $id,
                'user_id' => $uid,
                'good_name' => $good['good_name'],
                'good_type' => $good_type,
                'money' => $good['score'],
                'status' => $status
            ];
            Db::name('order')->insert($param);
            Db::table('gn_good')->where('id', $id)->inc('buy_num', 1)->dec('stock', 1)->update();
            ScoreLog::reduce(
                $uid,
                $good->score,
                'good_pay',
                '兑换商品',
                '兑换商品:' . $good['good_name']
            );
            $recordLog(1);
            // 提交事务
            Db::commit();
            return ['data' => $reward];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new Exception($e->getMessage());
        }
    }
    public function callRewardVal($user, $good)
    {
        $type = $good['good_type'];
        if ($type == 1) {
            $val = $this->addVipTime($user, $good);
        } else if ($type == 2) {
            $val =   $this->getFakeVal($good);
            Notification::send(getUid(), "你兑换的商品[" . $good['good_name'] . ']卡密为:' . $val);
        } else if ($type == 3) {
            $val = '';
            Notification::send(getUid(), "你兑换的商品[" . $good['good_name'] . '] 客服将会处理，请耐心等待');
        }
        return $val;
    }
    public function addVipTime($user, $good)
    {
        if (!User::checkVip(getUid())) {
            $vip_time = time() + $good['value'] * 3600 * 24;
        } else {
            $vip_time = $user['vip_time'] + $good['value'] * 3600 * 24;
        }
        return $vip_time;
    }
    public function getFakeVal($good)
    {
        $type = $good['value'];
        $fake = Fake::where(['type' => $type, 'status' => 0, 'is_load' => 0])->value('fake');
        if (!$fake) {
            throw new Exception('卡密库存不足,请联系客服处理');
        }
        return $fake;
    }
}
